import { useMemberStore, useSystemStore } from '@/stores'
const selfVersionCode = uni.getSystemInfoSync().appVersion //当前App版本号

export const ENV = 'dev' // 开发
// export const ENV = 'test' // 测试
// export const ENV = 'pro' // 生产
// export const ENV = 'hd' // 灰度
// if (ENV != 'dev' && ENV != 'test' && ENV != 'pro') {
//   try {
//     uni.request({
//       url: 'https://weapp.miyingbl.com/api/common/is_huidu',
//       method: 'GET',
//       data: {
//         banbenhao: selfVersionCode,
//       },
//       success: (res: any) => {
//         if (res.data.data) {
//           ENV = 'hd'
//         } else {
//           ENV = 'pro'
//         }
//       },
//     })
//   } catch (e) {}
// }

/**
 * @description 请求配置，根据项目配置
 * @property hd: 灰度环境
 * @property dev: 开发环境
 * @property pro: 生产环境
 * @property tokenKey: token在header中的key，配置多个时，需使用数组
 * @property tokenPrefix token在header中的前缀,需要加 Bearer 的时候配置
 * @property contentTypeKey: contentType的值 【json: application/json  form: application/x-www-form-urlencoded  formData: multipart/form-data】
 * @property headers: 单独配置请求头,勿在此配置token
 * @example uni.http({
        url: '/xx/xx/xx',
        method: 'POST',
        data:data,
        requestType: 'app',
        noAuth: true,
        tokenKey: 'token',
        tokenPrefix:'Bearer ',
        contentTypeKey: 'json',
        headers: {
        }
    })
 */
const BASE_LIST: any = {
  // 伴侣app
  app: {
    // 伴侣app
    dev: 'https://myblappdev.miyingbl.com/',
    pro: 'https://myblapp.miyingbl.com/',
    hd: 'https://myblapphd.miyingbl.com/',
    test: 'https://myblapptest.miyingbl.com/',
    tokenKey: 'token',
    tokenPrefix: '',
    contentTypeKey: '',
    headers: {},
  },
  shop: {
    // 商城
    dev: 'https://test.shop.miyingbl.com/api/',
    pro: 'https://shop.miyingbl.com/api/',
    hd: 'https://shop.hd.miyingbl.com/api/',
    test: 'https://shoptest.miyingbl.com/api/',
    tokenKey: 'X-Token',
    tokenPrefix: 'Bearer ',
    contentTypeKey: '',
    headers: { 'Form-type': 'app' },
  },
  service: {
    // 服务
    dev: 'https://test.service.miyingbl.com/api/',
    pro: 'https://service.miyingbl.com/api/',
    hd: 'https://service.hd.miyingbl.com/api/',
    test: 'https://servicetest.miyingbl.com/api/',
    tokenKey: 'X-Token',
    tokenPrefix: 'Bearer ',
    contentTypeKey: '',
    headers: { 'Form-type': 'app' },
  },
  baby: {
    // 咪婴女性
    dev: 'https://weappdev.miyingbl.com/',
    pro: 'https://weapp.miyingbl.com/',
    hd: 'https://weapphd.miyingbl.com/',
    test: 'https://weapptest.miyingbl.com/',
    tokenKey: 'Authorization',
    tokenPrefix: '',
    contentTypeKey: '',
    headers: {
      'source-client': 'miniapp',
      appid: 'wx9a0da8b1f22e92b0',
    },
  },
  skill: {
    // 技能
    dev: 'https://weappdev.miyingbl.com/',
    pro: 'https://weapp.miyingbl.com/',
    hd: 'https://weapphd.miyingbl.com/',
    test: 'https://weapptest.miyingbl.com/',
    tokenKey: 'Authorization',
    tokenPrefix: '',
    contentTypeKey: '',
    headers: {
      // appid: 'wxf1914035a5dec446',
    },
  },

  social: {
    // 社交
    dev: 'https://myblappdev.miyingbl.com/',
    pro: 'https://myblapp.miyingbl.com/',
    hd: 'https://weapphd.miyingbl.com/',
    test: 'https://weapptest.miyingbl.com/',
    tokenKey: 'token',
    tokenPrefix: '',
    contentTypeKey: '',
    headers: {},
  },
  company: {
    // 陪诊
    dev: 'https://weappdev.miyingbl.com/api/',
    pro: 'https://weapp.miyingbl.com/api/',
    test: 'https://weapptest.miyingbl.com/api/',
    hd: 'https://weapphd.miyingbl.com/api/',
    tokenKey: ['Authorization', 'token'],
    tokenPrefix: '',
    contentTypeKey: '',
    headers: {
      appid: 'wx27429c20663d34f9',
      platform: 'pz',
    },
  },
  bl: {
    // 伴侣小程序
    dev: 'https://weappdev.miyingbl.com/',
    pro: 'https://weapp.miyingbl.com/',
    hd: 'https://weapphd.miyingbl.com/',
    test: 'https://weapptest.miyingbl.com/',
    tokenKey: 'Authorization',
    tokenPrefix: '',
    contentTypeKey: '',
    headers: {
      appid: 'wxd66cae55aa470f87',
    },
  },
  life: {
    // 生活
    // dev: 'https://lifemydev.miyingbl.com/api/',
    dev: 'https://test.lifemy.miyingbl.com/api/',
    pro: 'https://lifemy.miyingbl.com/api/',
    hd: 'https://lifemy.hd.miyingbl.com/api/',
    test: 'https://lifemytest.miyingbl.com/api/',
    tokenKey: 'X-Token',
    tokenPrefix: '',
    contentTypeKey: '',
    headers: { 'Form-type': 'app' },
  },
  live: {
    // 直播
    dev: 'https://weappdev.miyingbl.com/',
    pro: 'https://weapp.miyingbl.com/',
    hd: 'https://weapphd.miyingbl.com/',
    test: 'https://weapptest.miyingbl.com/',
    tokenKey: 'Authorization',
    tokenPrefix: '',
    contentTypeKey: '',
    headers: {},
  },
  man: {
    // 咪婴男性
    dev: 'https://weappdev.miyingbl.com/',
    pro: 'https://weapp.miyingbl.com/',
    hd: 'https://weapphd.miyingbl.com/',
    test: 'https://weapptest.miyingbl.com/',
    tokenKey: 'Authorization',
    tokenPrefix: '',
    contentTypeKey: '',
  },

  cloud: {
    // 云服务
    dev: 'https://fc-mp-1362a735-5bd1-4d04-ae4a-02dc42bfd93a.next.bspapp.com/',
    pro: 'https://fc-mp-1362a735-5bd1-4d04-ae4a-02dc42bfd93a.next.bspapp.com/',
    tokenKey: 'Authorization',
    tokenPrefix: '',
    contentTypeKey: '',
    headers: {},
  },
}

const contentType: any = {
  json: 'application/json; charset=utf-8',
  form: 'application/x-www-form-urlencoded',
  formData: 'multipart/form-data',
}

const delKeys = ['contentTypeKey', 'requestType', 'noAuth']

const httpInterceptor = {
  invoke(options: any) {
    const store = useMemberStore()
    const token = store?.token
    let url = ''
    let header = {}

    if (!options.url?.startsWith('http') && !options.url?.startsWith('https')) {
      const _T = options.requestType
      if (_T) {
        url = BASE_LIST[_T][ENV] + options.url
        header = { ...BASE_LIST[_T].headers }
      } else {
        url = BASE_LIST['app'][ENV] + options.url
      }
    } else {
      url = options.url
    }

    options.url = url
    options.header = { ...options.header, ...header }
    options.timeout = 8000

    if (options.contentTypeKey) {
      options.header['Content-type'] = contentType[options.contentTypeKey]
    }

    if (token) {
      options.header.token = token
      const t = options.requestType
      if (!t) {
        options.header.token = token
      } else {
        const _TOKENS = BASE_LIST[t].tokenKey
        if (Array.isArray(_TOKENS)) {
          _TOKENS.forEach((item: any) => {
            options.header[item] = BASE_LIST[t]['tokenPrefix'] + token
          })
          return
        }
        options.header[_TOKENS] = BASE_LIST[t]['tokenPrefix'] + token
      }
    }
    delKeys.forEach((key) => {
      delete options[key]
    })
  },
}

uni.addInterceptor('request', httpInterceptor)

// uni.addInterceptor('uploadFile', httpInterceptor)
function GET_SYSTEMINFO() {
  const equipment = uni.getSystemInfoSync().deviceId
  const systemStore = useSystemStore()
  systemStore.setEquipment(equipment)
  return equipment
}

export function http<T>(options: any): Promise<T> {
  // updataEnv()

  const _From = options.from ? options.from : ''
  if (_From) delete options['from']
  const systemStore = useSystemStore()
  const equip = systemStore.equipment || GET_SYSTEMINFO() || 'H5'
  const data = Object.assign({}, options.data, { equipment: equip })
  options.data = data
  return new Promise((resolve, reject) => {
    // uni.request({
    // 	url: "blapp/v1/newpeople/userActiveCache",
    // 	method:"GET",
    // 	requestType:"app",
    //     success: (res: any) => {}
    // })
    uni.request({
      ...options,
      success: (res: any) => {
        if (res?.data?.message == '用户不存在') {
          const store = useMemberStore()
          store.clearToken()
          store.clearUserInfo()
        }
        resolve(res?.data)
      },
      fail: (err: any) => {
        reject(err)

        uni.showToast({
          title: '网络错误请重试',
          icon: 'error',
          mask: true,
        })
        setTimeout(() => {
          uni.hideToast()
        }, 2000)
      },
    })
  })
}

uni.http = http
